<?php
include 'function.php';
include "QinCaptcha.class.php";
//include 'FormProcessor/UserRegistration.php';
include "QinDb.class.php";
include "QinRegion.class.php";

class AccountController extends Zend_Controller_Action
{
  private $db;
  private $user;
  public function init()
  {
    $this->db = QinDb::instance();
    Zend_Db_Table::setDefaultAdapter($this->db);
  }

  public function indexAction()
  {
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /');

    // action body
    $this->view->captcha_url = QinCaptcha::create();
  }
  public function registerAction()
  {
    /* get province list */
    /* print "registar=============="; */
    $region = new QinRegion();
    $prov_list = $region->getProvinceList();
    /* print "----------------"; */
    /* print_r($prov_list); */
    $this->view->prov_list = $prov_list;
    $user = new Application_Model_User();
    $usermapper = new Application_Model_UserMapper();

    $this->view->postRegisterData = $this->getRequest()->getParams();
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');

    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /user');

	
    /* if ($fp->hasError()) */
    /*   $this->view->register_errors = $fp->getErrors(); */
    $this->view->captcha_url = QinCaptcha::create();
  }

  public function registerSubmitAction()
  {
    if ($this->getRequest()->isPost()) 
      {
	$form = $this->getRequest()->getPost();
	$msg = array();
	Zend_Session::start();
	$captcha_session = new Zend_Session_Namespace('captcha'); //在默认构造函数里实例化
	if (!isset($form['region_code']) || empty($form['region_code']))
	  $msg[] = "你没有选择地区。";
	else if (!isset($form['realname']) || empty($form['realname']))
	  $msg[] = "您没有填写姓名。";
	else if (!isset($form['username']) || empty($form['username']))
	  $msg[] = "您没有填写用户名。";
	else if (!isset($form['password']) || empty($form['password']))
	  $msg[] = "您没有填写密码。";
	else if (!isset($form['captcha']) || empty($form['captcha']))
	  $msg[] = "您没有填写验证码。";
	else if ($captcha_session->phrase != $form['captcha'])
	  {
	    $this->view->captcha_url = QinCaptcha::create();
	    $msg[] = "验证码错误";
	  }

	if (!$msg)
	  {
	    /* insert user */
	    include_once "QinUser.class.php";
	    $qin = new QinUser();
	    $res = $qin->addUser(array(
				       "username" => $form['username'],
				       "realname" => $form['realname'],
				       "gender" => $form['gender'],
				       "password" => $form['password'],
				       "region_code" => $form['region_code'],
				       /* "id_card_no" => $form[''], */
				       /* "qq_open_id" => $form[''], */
				       /* "avatar" => $form[''], */
				       /* "signature" => $form[''], */
				       ));
	    if($res['resp_id'] == '0000')
	      {
		/* login automatically */
		$user = new Application_Model_User();
		$user->set("username", $form['username']);
		$user->set("realname", $form['realname']);
		$user->set("gender", $form['gender']);
		$user->set("password", $form['password']);
		$user->set("region_code", $form['region_code']);
		$user->set("id", $res["resp_data"]["user_id"]);
		Zend_Session::start();
		$session = new Zend_Session_Namespace('account');
		$session->user = $user;
	      }
	    else
	      {
		$msg[] = $res['resp_data']['msg'];
	      }
	  }

	if ($msg)
	  {
	    $this->view->links = array(array("title"=>"返回首页", "url"=>"/"),
				       array("title"=>"继续注册", "url"=>"/account/register"));
	    $this->view->msg = implode("<br/>", $msg);
	  }
	else
	  {
	    $this->view->success = true;
	    $this->view->msg = "您已成功注册，现已登录。";
	    $this->view->links = array(array("title"=>"返回首页", "url"=>"/"),
				       array("title"=>"继续注册", "url"=>"/account/register"));	    
	  }
      }
  }
  public function registercompleteAction()
  {
    if ($this->getRequest()->getParam('type')=='email')
      {
	$this->view->msg = "已经发送了一封电子邮件到您的注册邮箱中，请在您的邮箱中确认您的注册后继续。";
      }
    else if ($this->getRequest()->getParam('type')=='username')
      {
	$this->view->msg = "感谢您的注册，现在您已登录。<br/><a href='/user/profile'>完善个人信息<a/>&nbsp;&nbsp;<a href='/'>返回首页</a>";
      }
  }

  public function loginAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      header('Location: /user');
    
    $message = '';

    if ($this->getRequest()->isPost())
      {
	$form = $this->getRequest()->getParams();
	if (empty($form['username']) || 
	    empty($form['password']))
	  {
	    $message = '请填写用户名或密码';
	  }
	else
	  {
	    if (strpos($form['username'], '@'))
	      $user_field = 'email';
	    else
	      $user_field = 'username';

	    // do the authentication
	    $authAdapter = new Zend_Auth_Adapter_DbTable($this->db,
							 'users',
							 $user_field,// 'email',//'username',
							 'password',
							 'md5(?)');
	    $authAdapter->setIdentity($form['username']);
	    $authAdapter->setCredential($form['password']);
	    $auth = Zend_Auth::getInstance();
	    $result = $auth->authenticate($authAdapter);

	    if ($result->isValid())
	      {
		$message = '登录成功';
		/* print $message; */

		$session->user  = new Application_Model_User();
		$usermapper = new Application_Model_UserMapper();
		$where = "$user_field = '{$form['username']}'";
		$usermapper->findObj($where, $session->user);

		// remember me
		if (isset($form['remember_me']) && $form['remember_me'] == 'on')
		  {
		    setcookie('username', $form['username'], time()+3600*24*7, "/");
		    setcookie('password', $form['password'], time()+3600*24*7, "/");
		    setcookie('remember_me', $form['remember_me'], time()+3600*24*7, "/");
		  }
		else
		  {
		    setcookie('username', "", time()-3600*24*7, "/");
		    setcookie('password', "", time()-3600*24*7, "/");
		    setcookie('remember_me', "", time()-3600*24*7, "/");
		  }

		header('Location: /user');
	      }
	    else
	      {
		switch ($result->getCode())
		  {
		  case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
		    $message = '用户名不存在';
		    break;
		  case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
		    $message = '用户名不唯一';
		    break;
		  case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:		
		    $message = '密码错误';
		    // remember me
		    break;
		  default:
		    $message = '登录失败';
		    break;
		  }
	      }
	  }
	$this->view->login_user = $form['username'];
	$this->view->login_passwd = $form['password'];
	$this->view->login_error = $message;

      }

    $this->view->captcha_url = QinCaptcha::create();
  }

  public function ajaxLoginAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id") > 0)
      {
	return $this->view->login = array('code'=>'0', 'message'=>'已成功登录');
      }
    $form = $this->getRequest()->getParams();
    if (empty($form['username']) || 
	empty($form['password']))
      {
	$message = '请填写用户名或密码';
      }
    else
      {
	if (strpos($form['username'], '@'))
	  $user_field = 'email';
	else
	  $user_field = 'username';

	// do the authentication
	$authAdapter = new Zend_Auth_Adapter_DbTable($this->db,
						     'users',
						     $user_field,// 'email',//'username',
						     'password',
						     'md5(?)');
	$authAdapter->setIdentity($form['username']);
	$authAdapter->setCredential($form['password']);
	$auth = Zend_Auth::getInstance();
	$result = $auth->authenticate($authAdapter);

	if ($result->isValid())
	  {
	    $message = '登录成功';
	    //print $message;

	    $session->user = new Application_Model_User();
	    $usermapper = new Application_Model_UserMapper();
	    $where = "$user_field = '{$form['username']}'";
	    $usermapper->findObj($where, $session->user);

	    // remember me
	    if (isset($form['remember_me']) && $form['remember_me'] == 'on')
	      {
		$message .= ";;remember me, ser username and password in cookie;;";
		setcookie('username', $form['username'], time()+3600*24*7, "/");
		setcookie('password', $form['password'], time()+3600*24*7, "/");
		setcookie('remember_me', $form['remember_me'], time()+3600*24*7, "/");
	      }
	    else
	      {
		$message .= ";;not remember me, clear cookie;;";
		setcookie('username', "", time()-3600*24*7, "/");
		setcookie('password', "", time()-3600*24*7, "/");
		setcookie('remember_me', "", time()-3600*24*7, "/");
	      }

	    //header('Location: /user');
	    $this->view->login = array('code' => '0', 'message' => $message, 'user' => $form['username']);
	  }
	else
	  {
	    switch ($result->getCode())
	      {
	      case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
		$message = '用户名不存在';
		break;
	      case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
		$message = '用户名不唯一';
		break;
	      case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:		
		$message = '密码错误';
		break;
	      default:
		$message = '登录失败';
		break;
	      }
	    $this->view->login = array('code' => $result->getCode(), 'message' => $message);
	  }
      }

  }
  public function logoutAction()
  {
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    $session->unsetAll();

    $this->view->captcha_url = QinCaptcha::create();
    header('Loaction: /account');
  }
}

